﻿using AutoMapper;
using B.S.Traceable.Domain.Entitiy;
using B.S.Traceable.ErrorCode;
using B.S.Traceable.Infrasturcture.Interfaces;
using B.S.Traceable.Write.Api.Application.Command.Traceable;
using MediatR;

namespace B.S.Traceable.Write.Api.Application.CommandHandler.Traceable
{
    public class CreateTraceableHandler : IRequestHandler<CreateTraceableCommand, ApiResult<object>>
    {

        private readonly IBaseRepository<TraceableModel> traRepo;
        private readonly IMapper mapper;
        private readonly IBaseRepository<PictureModel> picRepo;

        public CreateTraceableHandler(IBaseRepository<TraceableModel> traRepo, IMapper mapper, IBaseRepository<PictureModel> picRepo)
        {
            this.traRepo = traRepo;
            this.mapper = mapper;
            this.picRepo = picRepo;
        }

        public async Task<ApiResult<object>> Handle(CreateTraceableCommand request, CancellationToken cancellationToken)
        {
            ApiResult<object> result = new ApiResult<object>();

            var model=mapper.Map<TraceableModel>(request);
            model.Information = "0%";
            model.CreateName = "张三";
            model.CreateTime = DateTime.Now;
            model.UpdateName = "";
            model.UpdateTime = DateTime.UtcNow;
            var s = traRepo.Add(model).Result;
            if (s > 0)
            {
                result.Code = ApiEnums.Success;
                result.Msg = "添加成功";
                result.Data = s;

            }
            else
            {
                result.Code = ApiEnums.Failed;
                result.Msg = "添加失败";
                result.Data = -1;
            }
            return await  Task.FromResult(result);
        }

    }
}
